package code.juc.interview;

/**
 * 面试题:  使用两个线程, 交替打印0~100之间的数值.
 *
 * 1. 1个线程打印奇数；另外一个线程打印偶数.
 * 2. 需要两个线程交替执行.
 */
public class PrintOddEvenNumber {

    private static Integer count = 0;

    private static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread oddThread = new Thread(new PrintNumber(), "Odd");
        Thread evenThread = new Thread(new PrintNumber(), "even");
        oddThread.start();
        Thread.sleep(100);
        evenThread.start();
    }


    /**
     * 打印
     */
    static class PrintNumber implements Runnable {

        @Override
        public void run() {
            try {
                /**
                 * wait之后, 线程就需要一直等待被notify;
                 * 因此, 就可以保证, 两个线程之间交替执行.
                 */
                synchronized (LOCK) {
                    while (count <= 100) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                        LOCK.notify();

                        if (count <= 100) {
                            LOCK.wait();
                        }
                    }
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}